package com.java2104.service;

import com.java2104.entity.RCAttendance;
import com.java2104.entity.RCClass;
import com.java2104.entity.RCUser;
import com.java2104.mapper.RCAttendanceMapper;
import com.java2104.mapper.RCClassMapper;
import com.java2104.mapper.RCUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RCAttendanceService {
    @Autowired
    private RCAttendanceMapper attendanceMapper;
    @Autowired
    private RCClassMapper classMapper;
    @Autowired
    private RCUserMapper userMapper;
    //
    public boolean save(RCAttendance attendance) {
        //1.在出勤表中新加一条记录
        //班级学生总数 = 出勤人数 + 缺勤人数
        int studentNum = attendance.getAttendancePersonNum() + attendance.getAbsencePersonNum();
        //计算出勤率 = 出勤人数 ÷ 总人数
        float attendanceRate = (float)attendance.getAttendancePersonNum() / (float)studentNum;
        attendance.setAttendanceRate(attendanceRate);
        attendanceMapper.insert(attendance);//调用Mapper完成数据持久化
        //2.修改班级的点名次数，累计缺勤人数和累计缺勤率
        RCClass rcClass = classMapper.findByPrimaryKey(attendance.getRcClass().getId());
        rcClass.setCheckNum(rcClass.getCheckNum() + 1);//点名次数+1
        //累计缺勤人数 = 历史缺勤人次 + 本次点名缺勤人数
        rcClass.setAbsencePersonNum(rcClass.getAbsencePersonNum() + attendance.getAbsencePersonNum());
        //累计缺勤率 = 历史缺勤率 + 本次缺勤率（1-出勤率）
        rcClass.setAbsenceRate(rcClass.getAbsenceRate() + (1 - attendanceRate));
        classMapper.update(rcClass);//调用Mapper更新班级的出勤信息
        //3.修改点名人的点名次数
        RCUser user = userMapper.findByPrimaryKey(attendance.getRcUser().getId());
        user.setCheckNum(user.getCheckNum() + 1);
        userMapper.update(user);

        return true;
    }

    public List<RCAttendance> getList(int classId, int userId) {
        return attendanceMapper.findList(classId, userId);
    }

}
